import React, { useState, useEffect } from 'react';
import { Form, Input, Modal, Select, Upload, Button, message, Radio } from 'antd';
import { FormValueType } from '../data.d';
import { queryDeviceAttr } from '@/services/deviceattr';
import { queryDeviceList } from '@/services/device';
import SelectDeviceModal from '@/pages/authority/deviceattr/components/selectDeviceModal';



const { Option } = Select;
const FormItem = Form.Item;

export interface CreateFormProps {
  modalVisible: boolean;
  typelist: API.DictItem[];
  levellist:API.DictItem[];
  getAttrData: (id: number) => API.SysDeviceAttrItem;
  onSubmit: (values: FormValueType) => void;
  onCancel: () => void;
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit: handleAdd, onCancel } = props;


  const [form] = Form.useForm();
  
  const [attrType, setAttrType] = useState([]);
  const [selectDeviceModalVisible, handleDeviceModalVisible] = useState<boolean>(false);
  const [selectedKeys, setSelectedKeys] = useState<string>();
  const [selectedNames, setSelectedNames] = useState<string>();
  const [alarmLevel, setAlarmLevel] = useState<string>();
  const [alarmTypeList, setAlarmTypeList] = useState<API.DictItem[]>(props.typelist);
  const [levellist, setlevellist] = useState<API.DictItem[]>(props.levellist);

  const [deviceList, setDeviceList] = useState<API.DeviceItem[]>();

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    fieldsValue.ids = selectedKeys
    if(selectedKeys==null){
      alert('设备名称不能为空!')
    }else{
      form.resetFields();
      handleAdd(fieldsValue);
      setSelectedKeys('');
      setSelectedNames('');
    }
  };

  const changeType = async (value) => {
    if(value=='801'){
     if(form.getFieldValue("alarmType")==null){
       form.setFieldsValue({alarmType:'603'})
     }
    }else{
      if(form.getFieldValue("alarmType")==null){
        form.setFieldsValue({alarmType:'602'})
      }
    }
  };
  

  const getAlarmType = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.dictCode} value={item.dictCode}>
        {item.dictValue}
      </Option>
    ))
  }

  const getAlarmLevel = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.dictCode} value={item.dictCode}>
        {item.dictValue}
      </Option>
    ))
  }


  const getAttrType = (list) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.attrId} value={item.attrId}>
        {item.browseName}
      </Option>
    ))
  }

  const validatorValue = async (_: any, value: string) => {
    const promise = Promise;
    // if(value==null||value==""){
    //   return promise.reject("数值不能为空");
    // }
    if(Number.parseInt(value)>999999999999){
      return promise.reject("值不能超过99999999999");
    }
    if(_.field=='maxValue'&&Number(value)<Number(form.getFieldValue('minValue'))){
      return promise.reject("最大值不能小于最小值");
    }
    if(_.field=='minValue'&&Number(value)>Number(form.getFieldValue('maxValue'))){
      return promise.reject("最小值不能大于最大值");
    }
  
    return promise.resolve();
  };

  useEffect(() => {
    const setSelectData = async () => {
    
      // 获取变量名称
      const attrType = await queryDeviceAttr({
        current: 1,
        pageSize: 100
      });
      setDeviceList(await  queryDeviceList({useState:1}))  ; 
   
      setAttrType(attrType.data)
    };
    setSelectData();
  }, []);


  return (
    <Modal
      width={640}
      maskClosable={false}
      destroyOnClose
      title="新增报警规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Form
        {...formLayout}
        form={form}
      >
         <FormItem
          label="报警级别"
          name="alarmLevel"
          rules={[{ required: true, message: '报警级别不能为空' }]}
        >
          <Select placeholder="请选择" onChange={(value)=>changeType(value)}>
            {getAlarmLevel(levellist)}
          </Select>
        </FormItem>
        <FormItem
          label="报警类别"
          name="alarmType"
          rules={[{ required: true, message: '报警类别不能为空' }]}
        >
          <Select placeholder="请选择">
            {getAlarmType(alarmTypeList)}
          </Select>
        </FormItem>
        <FormItem
          label="报警规则名称"
          name="alarmName"
          rules={[{ required: true, max: 255, min: 2 }]}
        >
          <Input placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="设备名称"
          name="selectedNames"
          rules={[{ required: true, message: '设备名称不能为空'}]}          
        >
           
           <Input placeholder="请选择设备名称"  onClick={() => handleDeviceModalVisible(true)} /> 
        </FormItem>

        <FormItem
          label="变量名称"
          name="attrId"
          rules={[{ required: true, message: '变量名称不能为空' }]}
        >
          <Select placeholder="请选择">
            {getAttrType(attrType)}
          </Select>
        </FormItem>
      
        <FormItem
          label="最小值"
          name="minValue"
          rules={[{ required: true, message: '请输入最小值' },{validator: validatorValue}]}
     
        >
          <Input type='number' placeholder="请输入" autoComplete='off' />
        </FormItem>
        <FormItem
          label="最大值"
          name="maxValue"
          rules={[{validator: validatorValue}]}
        >
          <Input type='number' placeholder="请输入" autoComplete='off' />
        </FormItem>
      
        <FormItem
          label="启用状态"
          name="useState"
          initialValue={1}
        >
          <Radio.Group defaultValue={1}>
            <Radio value={1} >
              启用
            </Radio>
            <Radio value={0}>
              禁用
            </Radio>
          </Radio.Group>
        </FormItem>
        <FormItem
          label="处理建议"
          name="handleOpinions"
        >
          <Input.TextArea rows={3} placeholder="请输入" />
        </FormItem>
      </Form>
     {deviceList?<SelectDeviceModal
        onSubmit={async (ids, names, typeId) => {
          setSelectedKeys(ids);
         // setSelectedNames(names);
          form.setFieldsValue({selectedNames:names})
          handleDeviceModalVisible(false);
        }}
        deviceList={deviceList}
        onCancel={() => handleDeviceModalVisible(false)}
        modalVisible={selectDeviceModalVisible}
      />:null}
    </Modal>
  );
};

export default CreateForm;
